package com.aube.video;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.Build;
import android.os.CountDownTimer;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.asha.vrlib.MDVRLibrary;
import com.aube.R;
import com.aube.control.CardsController;
import com.aube.control.DataManager;
import com.aube.control.GoodsCardController;
import com.aube.guide.ViewTarget;
import com.aube.model.VideoHighlightData;
import com.aube.utils.AnimatorUtil;
import com.aube.views.FavorCart;
import com.aube.views.FavorList;
import com.aube.views.GoodsHotpotLayout;
import com.aube.views.HighlightVideoView;
import com.aube.views.PlayerSeekBar;
import com.aube.views.ResolutionSelector;
import com.aube.views.TouchableProgress;
import com.aube.views.vote.AnimatorHelper;
import com.huyn.baseframework.ImageLoader;
import com.huyn.baseframework.dynamicload.video.AbstractController;
import com.huyn.baseframework.dynamicload.video.AubeVideoPlayer;
import com.huyn.baseframework.dynamicload.video.IPlayController;
import com.huyn.baseframework.dynamicload.video.IPlayPresenter;
import com.huyn.baseframework.dynamicload.video.model.GoodsItem;
import com.huyn.baseframework.model.Category;
import com.huyn.baseframework.model.ChannelDetail;
import com.huyn.baseframework.net.BFJSONRequest;
import com.huyn.baseframework.net.HttpRequestLoader;
import com.huyn.baseframework.net.OpenApi;
import com.huyn.baseframework.share.ShareModule;
import com.huyn.baseframework.share.ShareType;
import com.huyn.baseframework.share.ShareUtil;
import com.huyn.baseframework.share.WeiboUtil;
import com.huyn.baseframework.utils.Constant;
import com.huyn.baseframework.utils.ImageParamUtils;
import com.huyn.baseframework.utils.PlayerUtil;
import com.huyn.baseframework.utils.SoftInputUtil;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.SysUtil;
import com.huyn.baseframework.utils.UmengUtils;
import com.huyn.baseframework.utils.UserUtil;
import com.huyn.baseframework.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by huyaonan on 16/3/22.
 */
public class PlayController implements View.OnClickListener, IPlayPresenter {

    private ChannelDetail mChannelInfo;
    private View mRootView;

    private View mTopController, mBottomController;

    private View mBack, mSetting, mTalk, mZoom, mShare;
    //vr control
    private ImageView mVrGesture, mVrGlass;
    private ImageView mPlay, mDanmu, mSound;
    private TextView mTitle;

    private PlayerSeekBar skbProgress;

    private TextView playDuration, videoDuration;

    private IPlayController iPlayController;

    private View mChatLayout, mChatSend;
    private EditText mChatContent;

    private AubeVideoPlayer mVideoHelper;

    private AtomicBoolean mIsOnTouchMode = new AtomicBoolean(false);

    private Context mContext;
    private TouchableProgress mProgress;

    private HighlightVideoView mHighlightVideoView;

    private View mOperationBottom, mOperationLogin;
    private View mLoginConfirm, mLoginCancel, mLoginTxt;

    private View mShareLayout, mShareWechat, mShareTimeline, mShareWeibo;

    private ResolutionSelector mResolutionSelector;

    private TextView mVideoTips;

    private AtomicBoolean mPauseByDanmu = new AtomicBoolean(false);
    private AtomicBoolean mAnimating = new AtomicBoolean(false);

    private String mDanmuContent;

    private AtomicBoolean mCanPerformEvent = new AtomicBoolean(false);

    private boolean mPauseByLogin = false;

    private FavorList mFavorList;
    private GoodsHotpotLayout mGoodsLayout;
    private FavorCart mFavorCart;

    private String mShareWeiboPicPath, mShareWechatPicPath;

    public PlayController(final View mRoot) {
        this.mContext = mRoot.getContext();
        this.mRootView = mRoot;

        LayoutInflater.from(mContext).inflate(R.layout.activity_aube_controller, (ViewGroup) mRoot.findViewById(R.id.play_controller_layout), true);

        mVideoTips = (TextView) mRoot.findViewById(R.id.video_tips);
        mProgress = (TouchableProgress) mRoot.findViewById(R.id.progress_indicator);
        mResolutionSelector = (ResolutionSelector) mRoot.findViewById(R.id.definition_selector);
        mTopController = mRoot.findViewById(R.id.playerTopLayout);
        mBottomController = mRoot.findViewById(R.id.playerBottomLayout);

        mFavorCart = (FavorCart) mRoot.findViewById(R.id.favor_cart);
        mGoodsLayout = (GoodsHotpotLayout) mRoot.findViewById(R.id.goods_root);
        mFavorList = (FavorList) mRoot.findViewById(R.id.favor_list);
        mFavorList.setAnchor(mTopController);
        mFavorList.initClickEvent(new FavorList.ICartClickListener() {
            @Override
            public void onClicked() {
                if(iPlayController != null)
                    iPlayController.rescheduleHideMessage();

                UmengUtils.reportUmengEvent(mContext, UmengUtils.CLICK_CART, UmengUtils.appendLabels(mChannelInfo.videoTitle, mChannelInfo.videoid));
            }

            @Override
            public void hideGoods() {
                if(iPlayController != null)
                    iPlayController.hideGoods();
            }
        });
        mBack = mRoot.findViewById(R.id.playBack);
        mSetting = mRoot.findViewById(R.id.playSetting);
        mShare = mRoot.findViewById(R.id.playShare);
        mTitle = (TextView) mRoot.findViewById(R.id.playTitle);

        mVrGesture = (ImageView) mRoot.findViewById(R.id.playGesture);
        mVrGlass = (ImageView) mRoot.findViewById(R.id.playGlass);

        playDuration = (TextView) mRoot.findViewById(R.id.playDuration);
        videoDuration = (TextView) mRoot.findViewById(R.id.videoDuration);
        playDuration.setText(PlayerUtil.millsecondsToMinutes(0));
        videoDuration.setText(PlayerUtil.millsecondsToMinutes(0));

        mPlay = (ImageView) mRoot.findViewById(R.id.playController);
        mPlay.setTag(R.id.play_state, true);//默认播放
        mTalk = mRoot.findViewById(R.id.playTalk);
        mDanmu = (ImageView) mRoot.findViewById(R.id.playDanmu);
        mZoom = mRoot.findViewById(R.id.playZoom);
        mSound = (ImageView) mRoot.findViewById(R.id.playSound);

        if(Constant.DEBUG)
            mSound.setVisibility(View.VISIBLE);
        else
            mSound.setVisibility(View.GONE);

        mOperationBottom = mRoot.findViewById(R.id.operation_bottom);
        mOperationLogin = mRoot.findViewById(R.id.operation_login);
        /**
         * 登录
         */
        mLoginCancel = mRoot.findViewById(R.id.login_cancel);
        mLoginConfirm = mRoot.findViewById(R.id.login_confirm);
        mLoginTxt = mRoot.findViewById(R.id.login_txt);

        mChatLayout = mRoot.findViewById(R.id.chat_layout);
        mChatSend = mRoot.findViewById(R.id.chat_send);
        mChatContent = (EditText) mRoot.findViewById(R.id.chat_txt);
        mChatSend.setOnClickListener(this);
        mChatLayout.setOnClickListener(this);

        int sizePaddingTop = SysUtil.getStatusBarHeight(mContext);
        if(sizePaddingTop > 0) {
            View status = mRoot.findViewById(R.id.status_bar);
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) status.getLayoutParams();
            params.height = sizePaddingTop;

            mChatLayout.setPadding(0, sizePaddingTop, 0, 0);
        }

        mChatContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    sendDanmu();
                }
                return false;
            }
        });

        skbProgress = (PlayerSeekBar) mRoot.findViewById(R.id.skbProgress);
        skbProgress.setOnSeekChangeListener(new PlayerSeekBar.OnSeekChangeListener() {
            @Override
            public void onStopTrackingTouch(PlayerSeekBar seekBar) {
                if (iPlayController != null) {
                    iPlayController.onProgressChanged(seekBar, seekBar.getProgress(), true, true);
                    iPlayController.sendHideMessage();
                }
                mIsOnTouchMode.set(false);

                endUpdateProgress();
            }

            @Override
            public void onStartTrackingTouch(PlayerSeekBar seekBar) {
                mIsOnTouchMode.set(true);
                if (iPlayController != null)
                    iPlayController.removeHideMessage();

                PlayController.this.onStartTrackingTouch();

                UmengUtils.reportUmengEvent(mContext, UmengUtils.TO_PROCEED_OR_RECEDE_BY_SEEKBAR, UmengUtils.appendLabels(mChannelInfo.videoid, mChannelInfo.videoTitle));
            }

            @Override
            public void onProgressChanged(PlayerSeekBar seekBar, int progress, boolean fromUser) {
                if (iPlayController != null)
                    iPlayController.onProgressChanged(seekBar, progress, fromUser, false);

                if (fromUser) {
                    playDuration.setText(PlayerUtil.millsecondsToMinutes(progress * mChannelInfo.duration * 1000 / 100));
                }

                startUpdateProgress(progress);
            }

            @Override
            public void onLocateProgress(int progress) {
                if (iPlayController != null) {
                    iPlayController.onLocateProgress(progress);
                    iPlayController.sendHideMessage();
                }
                mIsOnTouchMode.set(false);

                endUpdateProgress();
            }
        });

        mHighlightVideoView = (HighlightVideoView) mRoot.findViewById(R.id.video_highlight_group);

        mShareLayout = mRoot.findViewById(R.id.share_layout);
        mShareWechat = mRoot.findViewById(R.id.share_wechat);
        mShareTimeline = mRoot.findViewById(R.id.share_timeline);
        mShareWeibo = mRoot.findViewById(R.id.share_weibo);

        mShareLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                manageShareLayout(false);
            }
        });

        mShareWechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startShare(false);
                manageShareLayout(false);
            }
        });

        mShareTimeline.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startShare(true);
                manageShareLayout(false);
            }
        });

        mShareWeibo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startWeiboShare();
                manageShareLayout(false);
            }
        });

        mBack.setOnClickListener(this);
        mSetting.setOnClickListener(this);
        mShare.setOnClickListener(this);
        mVrGesture.setOnClickListener(this);
        mVrGlass.setOnClickListener(this);

        mZoom.setOnClickListener(this);
        mPlay.setOnClickListener(this);
        mTalk.setOnClickListener(this);
        mDanmu.setOnClickListener(this);

        mLoginConfirm.setOnClickListener(this);
        mLoginTxt.setOnClickListener(this);
        mLoginCancel.setOnClickListener(this);

        if(!Constant.DEBUG) {
            mSound.setVisibility(View.GONE);
        } else {
            mSound.setOnClickListener(this);
        }

        spyOnKeyboard(mRoot);
        skbProgress.setEnabled(false);
    }

    private void preloadPic() {
        if(StringUtils.isNotBlank(mChannelInfo.weiboPic) && StringUtils.isBlank(mShareWeiboPicPath)) {
            ImageLoader.getInstance(mContext).preloadBitmapToFile(mChannelInfo.weiboPic, new ImageLoader.IPreloadCallback<String>() {
                @Override
                public void onSuccess(String s) {
                    if(StringUtils.isNotBlank(s)) {
                        mShareWeiboPicPath = s;
                    }
                }

                @Override
                public void onFail() {

                }
            });
        }
        if(StringUtils.isNotBlank(mChannelInfo.sharePic) && StringUtils.isNotBlank(mShareWechatPicPath)) {
            ImageLoader.getInstance(mContext).preloadBitmapToFile(ImageParamUtils.getSquareUrl(mChannelInfo.sharePic, 200, 200), new ImageLoader.IPreloadCallback<String>() {
                @Override
                public void onSuccess(String s) {
                    if(StringUtils.isNotBlank(s)) {
                        mShareWechatPicPath = s;
                    }
                }

                @Override
                public void onFail() {

                }
            });
        }
    }

    public void init(ChannelDetail detial, Category category, Context context, final IPlayController controller) {
        this.mChannelInfo = detial;
        this.iPlayController = controller;
        mTitle.setText(detial.videoTitle);

        skbProgress.setVideoLength(mChannelInfo.duration);

        loadHighlightPoint(mChannelInfo.videoid);

        //服务端控制分享按钮
        if(StringUtils.isNotBlank(mChannelInfo.shareUrl))
            mShare.setVisibility(View.VISIBLE);

        reloadGoods();

        preloadPic();
    }

    public List<AbstractController> getControllers() {
        List<AbstractController> result = new ArrayList<>();
        result.add(new CardsController(mContext, (ViewGroup) mRootView.findViewById(R.id.card_root)));
        result.add(new GoodsCardController(mContext, (ViewGroup) mRootView.findViewById(R.id.goods_root)));
        return result;
    }

    public void switchGoodsHotpotSize(boolean fullscreen) {
        if(mGoodsLayout != null && mGoodsLayout.getVisibility() == View.VISIBLE)
            mGoodsLayout.switchSize(fullscreen);
    }

    public void removeGoodsFromFavor(String id) {
        mFavorList.remove(id);
    }

    public void addGoodsToFavor(List<GoodsItem> data) {
        mFavorList.addItems(data, true);
//        if(data == null)
//            return;
//        mFavorList.addItem(data, true);
    }

    public boolean interceptManageEvent() {
        if(isKeyboardOn()) {
            hideKeyboard();
            return true;
        }
        if(hideResolutionSelector())
            return true;
        if(mGoodsLayout.goodsViewRemoveable())
            return true;
        if(mFavorList.isShowing()) {
            mFavorList.hideList();
            return true;
        }
        if(mFavorCart.getVisibility() == View.VISIBLE) {
            mFavorCart.setVisibility(View.GONE);
            return true;
        }
        return false;
    }

    public void displayHotpot(int current) {
        if(mGoodsLayout != null)
            mGoodsLayout.diaplayHotpot(current == 0);
    }

    private void reloadGoods() {
        Iterator<Map.Entry<String, GoodsItem>> iterator = DataManager.getInstance(mContext).goodsIterator();
        while (iterator.hasNext()) {
            Map.Entry<String, GoodsItem> entry = iterator.next();
            mFavorList.addItem(entry.getValue(), false);
        }
    }

    /**
     * 有才展示
     */
    public void showGoodsCart() {
        if(mFavorCart.fill(DataManager.getInstance(mContext).goodsIterator())) {
            Animation anim = AnimationUtils.loadAnimation(mContext, R.anim.fade_in);
            anim.setDuration(200);
            anim.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                    mFavorCart.setVisibility(View.VISIBLE);
                }

                @Override
                public void onAnimationEnd(Animation animation) {

                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
            mFavorCart.startAnimation(anim);
        }
    }

    public void hideGoodsLayout() {
        if(mGoodsLayout != null)
            mGoodsLayout.hideGoods();
    }

    public void hideFavorCartIfVisible() {
        if(mFavorList != null && mFavorList.isShowing())
            mFavorList.hideList();
    }

    public void hideGoodsCart() {
        if(mFavorCart != null && mFavorCart.getVisibility() == View.VISIBLE)
            mFavorCart.setVisibility(View.GONE);
    }

    public void videoTxtTipsIn(String tips) {
        if(View.VISIBLE == mVideoTips.getVisibility())
            return;
        mVideoTips.setText(tips);
        ObjectAnimator anim = ObjectAnimator.ofFloat(mVideoTips, "translationY", mVideoTips.getHeight(), 0);
        anim.setDuration(300);
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                mVideoTips.setVisibility(View.VISIBLE);

                new CountDownTimer(3000, 1000) {

                    @Override
                    public void onTick(long millisUntilFinished) {

                    }

                    @Override
                    public void onFinish() {
                        videoTxtTipsOut();
                    }
                }.start();
            }
        });
        anim.start();
    }

    public void videoTxtTipsOut() {
//        mHandler.removeCallbacksAndMessages(null);
        if(View.VISIBLE == mVideoTips.getVisibility()) {
            ObjectAnimator anim = ObjectAnimator.ofFloat(mVideoTips, "translationY", 0, mVideoTips.getHeight());
            anim.setDuration(300);
            anim.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mVideoTips.setVisibility(View.INVISIBLE);
                    mAnimating.set(false);
                }
            });
            anim.start();
        }
    }

    public void setVideoHelper(AubeVideoPlayer helper) {
        this.mVideoHelper = helper;
    }

    /**
     * 刷新内容
     * @param channelDetail
     */
    public void updateContent(ChannelDetail channelDetail) {
        mChannelInfo = channelDetail;
        //服务端控制分享按钮
        if(StringUtils.isNotBlank(mChannelInfo.shareUrl))
            mShare.setVisibility(View.VISIBLE);

        updateTitle(channelDetail.videoTitle);

        preloadPic();
    }

    private void sendDanmu() {
        String s = mChatContent.getText().toString();

        //清除发送的内容和焦点并隐藏键盘
        mChatContent.clearFocus();
        SoftInputUtil.hideShow(mChatContent);

        if(iPlayController != null)
            iPlayController.hideToolsBar();

        mDanmuContent = s;
    }

    public void setupResolutions(Map<Integer, String> definitions, int currentCode) {
        mResolutionSelector.fill(definitions, currentCode, new ResolutionSelector.ISelectorListener() {
            @Override
            public void onSelect(String des, int type) {
                if (iPlayController != null) {
                    iPlayController.changeDefinition(des, type);
                    updateState(false);
                }

                resolutionSelectorOut();
            }

            @Override
            public void dismiss() {
                resolutionSelectorOut();
            }
        });
    }

    private void resolutionSelectorOut() {
        if(mAnimating.get())
            return;
        mAnimating.set(true);

        AnimatorUtil.animFloat(300, 1, 0, new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                mResolutionSelector.setAlpha(value);
                mResolutionSelector.setTranslationX(mResolutionSelector.getWidth() * (1 - value));
            }
        }, new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mResolutionSelector.setVisibility(View.GONE);
                mAnimating.set(false);
            }
        });
    }

    private void resolutionSelectorIn() {
        if(mAnimating.get())
            return;
        mAnimating.set(true);
        mResolutionSelector.setAlpha(0f);
        mResolutionSelector.setVisibility(View.VISIBLE);

        UmengUtils.reportUmengEvent(mContext, UmengUtils.TO_VIDEO_SETTING, UmengUtils.appendLabels(mChannelInfo.videoid, mChannelInfo.videoTitle));

        AnimatorUtil.animFloat(300, 0, 1, new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                mResolutionSelector.setAlpha(value);
                mResolutionSelector.setTranslationX(mResolutionSelector.getWidth()*(1-value));
            }
        }, new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mAnimating.set(false);
            }
        });
    }

    public boolean hideResolutionSelector() {
        if(mAnimating.get()) {
            mAnimating.set(false);
            return true;
        }
        if(mResolutionSelector.getVisibility() == View.VISIBLE) {
            resolutionSelectorOut();
            return true;
        }
        return false;
    }

    public void play() {
        mPlay.setImageResource(R.drawable.icon_pause);
        mPlay.setTag(R.id.play_state, true);

        if(iPlayController != null)
            iPlayController.start();

        if(StringUtils.isNotBlank(mDanmuContent)) {
            if(iPlayController != null)
                iPlayController.sendDanmu(mDanmuContent, mChannelInfo.videoid, (int) (mVideoHelper.getCurrentProgress()));
            mDanmuContent = null;

            UmengUtils.reportUmengEvent(mContext, UmengUtils.SEND_DANMU, UmengUtils.appendLabels(mChannelInfo.videoid, mChannelInfo.videoTitle));
        }

        //force hideTitle keyboard
        SoftInputUtil.hideShow(mChatContent);
    }

    @Override
    public void showPauseAD() {
        if(iPlayController != null)
            iPlayController.showPauseAD();
    }

    @Override
    public void hidePauseAD() {
        if(iPlayController != null)
            iPlayController.hidePauseAD();
    }

    public void pause() {
        mPlay.setImageResource(R.drawable.icon_play);
        mPlay.setTag(R.id.play_state, false);
        mVideoHelper.pausePlay();

        if(iPlayController != null) {
            iPlayController.pause();
            iPlayController.pauseDanmu();
        }
    }

    public void pauseWhenFreeze() {
        if(iPlayController != null)
            iPlayController.pauseWhenFreeze();
    }

    public void pauseWhenLogin() {
        boolean state = (boolean) mPlay.getTag(R.id.play_state);
        if(!state)
            return;
        mPauseByLogin = true;
        pause();
    }

    public void resumeFromLogin() {
        if(mPauseByLogin)
            play();
        mPauseByLogin = false;
    }

    public boolean isPlaying() {
        if(iPlayController.isLowExperience()) {
            if(mPlay != null)
                return (boolean) mPlay.getTag(R.id.play_state);
        } else {
            if (mVideoHelper != null && mVideoHelper.isPlaying())
                return true;
        }
        return false;
    }

    public void enableSeekBar() {
        if(skbProgress.isEnabled())
            return;
        skbProgress.setEnabled(true);
    }

    private boolean isLogin() {
        return UserUtil.isUserLogin();
//        return true;
    }

    public void toWriteDammu(boolean hideTools) {
        mDanmuContent = null;
        if(hideTools) {
            hideLoginTools();
//            mOperationLogin.setVisibility(View.GONE);
//            mOperationBottom.setVisibility(View.VISIBLE);
        }

        //show input box
        mChatLayout.setVisibility(View.VISIBLE);
        //show keyboard
        mChatContent.requestFocus();
        SoftInputUtil.showSoftInput(mChatContent);

        //暂停视频和弹幕
//        if(mVideoHelper.isPlaying()) {
        if(isPlaying()) {
            if(iPlayController != null)
                iPlayController.clearHideMsg();
            pause();
        }
        mPauseByDanmu.set(true);

        manageEditContent(true);
    }

    private void showLoginTools() {
        if(mAnimating.get())
            return;
        mAnimating.set(true);
        Animation animIn = AnimationUtils.loadAnimation(mContext, R.anim.card_in);
        animIn.setDuration(300);
        animIn.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                mOperationLogin.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        Animation animOut = AnimationUtils.loadAnimation(mContext, R.anim.card_out);
        animOut.setDuration(300);
        animOut.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mOperationBottom.setVisibility(View.GONE);
                mHighlightVideoView.setVisibility(View.GONE);
                mAnimating.set(false);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        mOperationBottom.startAnimation(animOut);
        mHighlightVideoView.startAnimation(animOut);
        mOperationLogin.startAnimation(animIn);
    }

    private void hideLoginTools() {
        if(mAnimating.get())
            return;
        mAnimating.set(true);
        Animation animIn = AnimationUtils.loadAnimation(mContext, R.anim.card_in);
        animIn.setDuration(300);
        animIn.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                mOperationBottom.setVisibility(View.VISIBLE);
                mHighlightVideoView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        Animation animOut = AnimationUtils.loadAnimation(mContext, R.anim.card_out);
        animOut.setDuration(300);
        animOut.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mOperationLogin.setVisibility(View.GONE);
                mAnimating.set(false);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        mOperationBottom.startAnimation(animIn);
        mHighlightVideoView.startAnimation(animIn);
        mOperationLogin.startAnimation(animOut);
    }

    private int previousHeightDifference = 0;
    private void spyOnKeyboard(final View mRoot) {
        mRoot.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {

                    @Override
                    public void onGlobalLayout() {
                        Rect r = new Rect();
                        mRoot.getWindowVisibleDisplayFrame(r);

                        int[] locations = {0, 0};
                        mChatLayout.getLocationOnScreen(locations);

                        int pos = locations[1] + mChatLayout.getHeight();

                        int screenHeight = mRoot.getRootView().getHeight();
                        int heightDifference = screenHeight - (r.bottom);

                        if (heightDifference > 100) {
                            if (previousHeightDifference != heightDifference) {
                                previousHeightDifference = heightDifference;
                                if (pos > r.bottom)
                                    manageEditContent(true);
                            }
                        } else {
                            if (previousHeightDifference != heightDifference) {
                                previousHeightDifference = heightDifference;
                                manageEditContent(false);
                            }
                        }
                    }
                });
    }

    public boolean isKeyboardOn() {
        return mChatLayout.getVisibility() == View.VISIBLE;
    }

    public void hideKeyboard() {
        SoftInputUtil.hideShow(mChatContent);
    }

    private void manageEditContent(final boolean show) {
        if(mAnimating.get())
            return;
        mAnimating.set(true);
        if(iPlayController != null) {
            iPlayController.manageFlingEvent(!show);
        }

        if(!show) {
            if(mPauseByDanmu.get()) {
                mPauseByDanmu.set(false);

                play();
            }
        }

        Animation anim = AnimationUtils.loadAnimation(mContext, show ? R.anim.push_top_in : R.anim.push_top_out);
        anim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if (!show) {
                    mChatLayout.setVisibility(View.GONE);
                    mChatContent.setText("");
                }
                mAnimating.set(false);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        mChatLayout.startAnimation(anim);
    }

    private static final int DURATION = 300;
    public void manageToolVisibleState(final boolean hide) {
        manageToolVisibleState(hide, true);
    }
    public void manageToolVisibleState(final boolean hide, boolean manageStatus) {
        ValueAnimator alphaAnim = hide ? ValueAnimator.ofFloat(1f, 0f) : ValueAnimator.ofFloat(0f, 1f);
        alphaAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                mTopController.setAlpha(value);
                mBottomController.setAlpha(value);
                mFavorList.setAlpha(value);
            }
        });
        alphaAnim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                if(!hide) {
                    mTopController.setVisibility(View.VISIBLE);
                    mBottomController.setVisibility(View.VISIBLE);
                    mFavorList.manageVisible(true, true);
                }
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                if(iPlayController != null)
                    iPlayController.onUpdateToolState(!hide);

                if(hide) {
                    mTopController.setVisibility(View.GONE);
                    mBottomController.setVisibility(View.GONE);
                    mFavorList.manageVisible(true, false);
                }
            }
        });
        alphaAnim.setDuration(DURATION);
        alphaAnim.start();
    }

    public int[] getCartLocation() {
        if(mBottomController != null) {
            int[] locations = new int[2];
            mBottomController.getLocationInWindow(locations);
            int yPos = locations[1];
            if(mBottomController.getVisibility() == View.VISIBLE)
                yPos -= mBottomController.getHeight();
            return new int[]{locations[0]+mFavorList.getIconWidth(), yPos};
        }
        return null;
    }

    public void onDestroy() {
    }

    @Override
    public boolean shouldRequestStoragePermission() {
        if(iPlayController != null)
            return iPlayController.shouldRequestStoragePermission();
        return false;
    }

    @Override
    public void onBufferingStartEvent() {
    }

    @Override
    public void onBufferingEndEvent() {
    }

    public void switchVideo(ChannelDetail channelDetail) {
        if(iPlayController != null) {
            iPlayController.switchVideo(channelDetail);
        }
    }

    @Override
    public void continueAfterPermissionGet() {
        startWeiboShare();
    }

    public boolean onBackPressed() {
        if(mShareLayout != null && mShareLayout.getVisibility() == View.VISIBLE) {
            manageShareLayout(false);
            return true;
        }
        return false;
    }

    public void endPlay() {
        mTopController.setVisibility(View.VISIBLE);
        mBottomController.setVisibility(View.VISIBLE);

        mPlay.setImageResource(R.drawable.icon_play);
        mPlay.setTag(R.id.play_state, false);
        //播放结束后不暂停弹幕
//        mDanmuHelper.onPause();
    }
    
    public boolean updateProgress(long current, long duration) {
        if(skbProgress.isVideoLengthEmpty()) {
            skbProgress.setVideoLength(duration/1000);
            mHighlightVideoView.setVideoLength(duration/1000);
        }

        if(!mIsOnTouchMode.get() && duration != 0) {
            skbProgress.setProgress((int) (current * skbProgress.getMax() / duration));

            playDuration.setText(PlayerUtil.millsecondsToMinutes(current));
            videoDuration.setText(PlayerUtil.millsecondsToMinutes(duration));

            if(iPlayController != null)
                iPlayController.manageMessageProgress(current);
        }
        return !mIsOnTouchMode.get();
    }

    public void updateBuffer(int progress) {
        skbProgress.setSecondaryProgress(progress);
    }

    public void reserveFullScreen(boolean exitMultiVideo) {
        if(exitMultiVideo) {
            mTitle.setText(mChannelInfo.videoTitle);
            mTitle.setVisibility(View.VISIBLE);
//            mSetting.setVisibility(View.VISIBLE);
//            mShare.setVisibility(View.VISIBLE);
            mZoom.setVisibility(View.GONE);

            initToolBar(true);
        } else {
            mTitle.setVisibility(View.INVISIBLE);
//            mShare.setVisibility(View.GONE);
//            mSetting.setVisibility(View.GONE);
            mZoom.setVisibility(View.GONE);

            AnimatorHelper.alphaAnim(mTitle, 1, 0, false);
            AnimatorHelper.alphaAnim(mZoom, 1, 0);

            //立即隐藏视频设置
            resolutionSelectorOut();

            initToolBar(false);
        }
    }

    /**
     * 多镜头进入全屏模式
     * @param title
     */
    public void toFullScreen(String title, boolean isVr) {
        mTitle.setText(title);
        mTitle.setVisibility(View.VISIBLE);
//        mSetting.setVisibility(View.GONE);
//        mShare.setVisibility(View.GONE);
        mZoom.setVisibility(View.VISIBLE);

        if(isVr) {
            mVrGesture.setVisibility(View.VISIBLE);
            mVrGlass.setVisibility(View.VISIBLE);
        } else {
            mVrGesture.setVisibility(View.GONE);
            mVrGlass.setVisibility(View.GONE);
        }

        AnimatorHelper.alphaAnim(mTitle, 0, 1, false);
        AnimatorHelper.alphaAnim(mZoom, 0, 1);

        //展示引导
        iPlayController.showScaleGuide();
    }

    public void initToolBar(boolean onMajorVideo) {
        if(iPlayController != null && iPlayController.isVrMode(onMajorVideo)) {
            mVrGesture.setVisibility(View.VISIBLE);
            mVrGlass.setVisibility(View.VISIBLE);
        } else {
            mVrGesture.setVisibility(View.GONE);
            mVrGlass.setVisibility(View.GONE);
        }
    }

    public View getZoomView() {
        return mZoom;
    }

    public void updateTitle(String title) {
        mTitle.setText(title);
    }

    /**
     * 通过触摸控制快进或者快退,需要屏蔽skbprogress的其他动作
     * @param forward
     * @param ratio
     * @param doSeek
     */
    private long duration = 0;
    private long currentProgress = 0;
    public void manageProgress(boolean forward, float ratio, boolean doSeek) {
        try {
            if(!mCanPerformEvent.get())
                return;
            mIsOnTouchMode.set(!doSeek);
            if(duration == 0)
                duration = mVideoHelper.getDuration();
            if(currentProgress == 0)
                currentProgress = mVideoHelper.getCurrentProgress();
            int target = (int) (duration * ratio);

            if(iPlayController != null)
                iPlayController.hideCart();

            if(doSeek) {
                int targetPosition = skbProgress.jumpToNearestHighlight(ratio);
                if(targetPosition > 0) {
                    target = targetPosition;
                    ratio = target * 1f / duration;
                }

                mProgress.updateProgress(forward, ratio, currentProgress, duration);


                if(iPlayController != null)
                    iPlayController.updatePlay(target);

                mProgress.hide();

                UmengUtils.reportUmengEvent(mContext, UmengUtils.TO_PROCEED_OR_RECEDE_BY_GESTURE, UmengUtils.appendLabels(mChannelInfo.videoid, mChannelInfo.videoTitle));

                duration = 0;
                currentProgress = 0;
            } else {
                mProgress.updateProgress(forward, ratio, currentProgress, duration);
            }

            int progress = (int) (ratio * skbProgress.getMax());
            skbProgress.setProgress(progress);
            playDuration.setText(PlayerUtil.millsecondsToMinutes(target));

            startUpdateProgress(progress);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 取消seek
     */
    public void cancelSeek() {
        if(!mCanPerformEvent.get())
            return;
        if(mIsOnTouchMode.get()) {
            mIsOnTouchMode.set(false);

            int target = (int) mVideoHelper.getCurrentProgress();
            //update text and seekbar
            float ratio = target * 1f / mVideoHelper.getDuration();

            mProgress.hide();
            skbProgress.setProgress((int) (ratio * skbProgress.getMax()));
            playDuration.setText(PlayerUtil.millsecondsToMinutes(target));

        }
    }

    public void onStartTrackingTouch() {
        if(mHighlightVideoView != null)
            mHighlightVideoView.onStartTrackingTouch(mVideoHelper.getCurrentProgress());
    }

    /**
     * 重置controller的信息
     */
    public void endUpdateProgress() {
        if(mHighlightVideoView != null)
            mHighlightVideoView.endUpdateProgress();

        if(iPlayController != null)
            iPlayController.rescheduleHideMessage();
    }

    public void startUpdateProgress(int progress) {
        if(mHighlightVideoView != null)
            mHighlightVideoView.startUpdateProgress(progress);

        if(iPlayController != null)
            iPlayController.clearHandlerMsg();
    }

    /**
     * 是否开始播放了
     * @param state
     */
    public void updateState(boolean state) {
        mCanPerformEvent.set(state);
        skbProgress.enableSeek(state);
        if(iPlayController != null)
            iPlayController.manageFlingEvent(state);

        if(mHighlightVideoView != null)
            mHighlightVideoView.setVisibility(state ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if(id == R.id.playBack) {
            if (iPlayController != null) {
                if (iPlayController.onBack())
                    return;
                iPlayController.finish();
            }
            return;
        }
        if(!mCanPerformEvent.get())
            return;
        if(iPlayController != null)
            iPlayController.rescheduleHideMessage();
        clickView(id);
    }

    private void clickView(int id) {
        if(id == mLoginConfirm.getId() || id == mLoginTxt.getId()) {
            UmengUtils.reportUmengEvent(mContext, UmengUtils.LOGIN_BEFORE_DANMU, UmengUtils.appendLabels(mChannelInfo.videoid, mChannelInfo.videoTitle));
            if(iPlayController != null)
                iPlayController.doLogin();
        } else if(id == mLoginCancel.getId()) {
            hideLoginTools();
        } else if(id == mSound.getId()) {
            if (iPlayController == null)
                return;
            if(iPlayController.isSoundOn()) {
                iPlayController.manageSound(false);
                mSound.setImageResource(R.drawable.icon_voiceon);
            } else {
                iPlayController.manageSound(true);
                mSound.setImageResource(R.drawable.icon_voiceoff);
            }
        } else if(id == mDanmu.getId()) {
            if(iPlayController == null)
                return;
            //show or hideTitle danmu
            if(iPlayController.isDanmuOn()) {
                iPlayController.hideDanmu();
                mDanmu.setImageResource(R.drawable.icon_dan);
            } else {
                iPlayController.showDanmu();
                mDanmu.setImageResource(R.drawable.icon_closedan);
            }
        } else if(id == mTalk.getId()) {
            if(isLogin()) {
                toWriteDammu(false);
            } else {
                showLoginTools();
            }
        } else if(id == mPlay.getId()) {
            //pause or play
            mPauseByDanmu.set(false);
//            if(mVideoHelper.isPlaying()) {
            if(isPlaying()) {
                pause();

                showPauseAD();
            } else {
                play();

                hidePauseAD();
            }
        } else if(id == mZoom.getId()) {
            if(iPlayController != null)
                iPlayController.reverseFromFullScreen();
        } else if(id == mSetting.getId()) {
            resolutionSelectorIn();
        } else if(id == mChatSend.getId()) {
            sendDanmu();
        } else if(id == mChatLayout.getId()) {
            //阻止点击事情向下传递
        } else if(id == mVrGesture.getId()) {
            if(iPlayController != null) {
                int mode = iPlayController.switchInteractiveMode();

                if(mode == MDVRLibrary.INTERACTIVE_MODE_MOTION_WITH_TOUCH) {
                    mVrGesture.setImageResource(R.drawable.icon_vr_motionlock);
                } else {
                    mVrGesture.setImageResource(R.drawable.icon_vr_motion);
                }
            }
        } else if(id == mVrGlass.getId()) {
            if(iPlayController != null) {
                int mode = iPlayController.switchDisplayMode();

                if(mode == MDVRLibrary.DISPLAY_MODE_GLASS) {
                    mVrGlass.setImageResource(R.drawable.icon_vr_glassoff);
                } else {
                    mVrGlass.setImageResource(R.drawable.icon_vr_glasson);
                }
            }
        } else if(id == mShare.getId()) {
            manageShareLayout(true);
        }
    }

    private void manageShareLayout(final boolean show) {
        ValueAnimator anim = ValueAnimator.ofFloat(show ? 0 : 1, show ? 1 : 0);
        anim.setDuration(400);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();

                mShareLayout.setAlpha(value);
                mShareWechat.setAlpha(value);
                mShareWeibo.setAlpha(value);
                mShareTimeline.setAlpha(value);

                if(show) {
                    float translationY = mShareWechat.getHeight() * (1-value);
                    mShareWechat.setTranslationY(translationY);
                    mShareWeibo.setTranslationY(translationY);
                    mShareTimeline.setTranslationY(translationY);
                }
            }
        });
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                if(!show) {
                    mShareLayout.setVisibility(View.GONE);

                    if(!isPlaying())
                        play();
                }
            }

            @Override
            public void onAnimationStart(Animator animation) {
                if(show) {
                    mShareLayout.setAlpha(0f);
                    mShareWechat.setAlpha(0f);
                    mShareWeibo.setAlpha(0f);
                    mShareTimeline.setAlpha(0f);
                    mShareLayout.setVisibility(View.VISIBLE);

                    if(isPlaying())
                        pause();
                }
            }
        });
        anim.start();
    }

    private void startWeiboShare() {
        if(StringUtils.isNotBlank(mChannelInfo.weiboContent) && StringUtils.isNotBlank(mShareWeiboPicPath)) {
            if(shouldRequestStoragePermission())
                return;
            if(StringUtils.isNotBlank(mShareWeiboPicPath)) {
                String destFile = Utils.copyToFile(mShareWeiboPicPath);
                if (StringUtils.isNotBlank(destFile) && !"ERROR".equalsIgnoreCase(destFile)) {
                    ShareModule shareModule = new ShareModule();
                    shareModule.content = mChannelInfo.weiboContent;
                    WeiboUtil.getInstance((Activity) mContext).sendMessage((Activity) mContext, WeiboUtil.getImageObj(destFile, mChannelInfo.weiboContent), shareModule);
                    UmengUtils.reportUmengEvent(mContext, UmengUtils.SHARE_VIA_WEIBO, mChannelInfo.videoid + "_" + mChannelInfo.videoTitle);
                    return;
                }
                Utils.showToast(mContext, "分享内容为空");
            }
        } else {
            Utils.showToast(mContext, "分享内容为空");
        }
    }

    private void startShare(final boolean isTimeline) {
        if(StringUtils.isNotBlank(mShareWechatPicPath)) {
            ImageLoader.getInstance(mContext).preloadBitmap(mShareWechatPicPath, new ImageLoader.IPreloadCallback<Bitmap>() {
                @Override
                public void onSuccess(Bitmap bitmap) {
                    startShare(bitmap, isTimeline);
                }

                @Override
                public void onFail() {

                }
            });
        } else {
            startShare(null, isTimeline);
        }
    }

    private void startShare(Bitmap bitmap, boolean isTimeline) {
        ShareModule shareModule = new ShareModule();
        shareModule.mShareChannel = isTimeline ? ShareType.TIMELINE : ShareType.WECHAT;
        shareModule.WeiXinTpye = ShareModule.TYPE_VIDEO;
        shareModule.shareUrl = mChannelInfo.shareUrl;
        shareModule.title = mChannelInfo.shareTitle;
        shareModule.content = mChannelInfo.shareContent;
        shareModule.reportData = mChannelInfo.videoid + "_" + mChannelInfo.videoTitle;
        if(bitmap != null)
            shareModule.imgBm = bitmap;

        ShareUtil.startShare(mContext, shareModule);
    }

    /**
     * 获取节目亮点
     * @param videoid
     */
    public void loadHighlightPoint(final String videoid) {
        HashMap<String, String> parameterMap = new HashMap<>();
        parameterMap.put(OpenApi.API_METHOD, OpenApi.HIGHLIGHT_VIDEO_MILESTONE);
        parameterMap.put("videoid", videoid);
        BFJSONRequest request = new BFJSONRequest(VideoHighlightData.class, parameterMap, new Response.Listener<VideoHighlightData>() {

            @Override
            public void onResponse(VideoHighlightData response) {
                if(!response.success()) {
                    return;
                }

                //填充到节点
                mHighlightVideoView.setupViews(new ViewTarget(skbProgress), response.getData(), mChannelInfo.duration);
                skbProgress.showHighlightPoints(response.getData());
            }

            @Override
            public void onErrorResponse(VolleyError error) {
            }

            @Override
            public void onStart() {
            }
        });
        HttpRequestLoader.getInstance(mContext).startCacheLoader("", request, true);
    }

}
